import { ref, reactive, computed, nextTick } from 'vue';
import type { Ref } from 'vue';
import type { Position } from '../types';
import type { NodeType } from '../types';
import { useWorkflowStore, type WorkflowStore } from '@/stores/workflow';

/**
 * 节点拖拽功能组合式函数
 * @param svgContainer SVG容器元素引用
 * @param updateTransform 更新变换的回调函数
 */
export function useNodeDragging(svgContainer: Ref<SVGSVGElement | null>, updateTransform: () => void) {
  // 工作流状态管理
  const workflowStore: WorkflowStore = useWorkflowStore();
  
  // 拖拽状态
  const isDragging = ref(false);          // 是否正在拖拽
  const draggedNode = ref<NodeType | null>(null);  // 当前拖拽的节点
  const dragPosition = reactive<Position>({ x: 0, y: 0 });  // 拖拽位置
  const dragOffset = reactive<Position>({ x: 0, y: 0 });    // 拖拽偏移量
  const isOverSvg = ref(false);           // 是否在SVG容器上方

  /**
   * 将鼠标坐标转换为SVG坐标系中的位置
   * @param e 拖拽事件对象
   * @returns 转换后的位置坐标
   */
  const convertToSVGCoordinates = (e: DragEvent): Position => {
    if (!svgContainer.value) return { x: 0, y: 0 };

    // 获取SVG容器的边界矩形
    const svgRect = svgContainer.value.getBoundingClientRect();
    const contentGroup = svgContainer.value.querySelector('.content-group');
    if (!contentGroup) return { x: 0, y: 0 };

    // 获取当前变换信息
    const transform = contentGroup.getAttribute('transform') || '';
    const translateMatch = transform.match(/translate\(([-\d.]+),([-\d.]+)\)/);
    const scaleGroup = contentGroup.querySelector('g');
    const scaleTransform = scaleGroup?.getAttribute('transform') || '';
    const scaleMatch = scaleTransform.match(/scale\(([\d.]+)\)/);
    
    // 解析缩放和平移值
    const scale = scaleMatch ? parseFloat(scaleMatch[1]) : 1;
    const translateX = translateMatch ? parseFloat(translateMatch[1]) : 0;
    const translateY = translateMatch ? parseFloat(translateMatch[2]) : 0;

    // 计算实际位置
    return {
      x: (e.clientX - svgRect.left - translateX) / scale,
      y: (e.clientY - svgRect.top - translateY) / scale
    };
  };

  /**
   * 处理节点开始拖拽
   * @param e 拖拽事件对象
   * @param node 被拖拽的节点
   */
  const handleNodeDragStart = (e: DragEvent, node: NodeType) => {
    console.log('拖拽开始前选中状态:', workflowStore.state.selectedNodeIds);
    if (!e.dataTransfer) return;
    isDragging.value = true;
    draggedNode.value = node;
	
    // 设置拖拽数据和效果
    e.dataTransfer.setData('node-type', node.type);
    e.dataTransfer.effectAllowed = 'copy';
    
    // 创建拖拽图像
    const dragImage = document.createElement('div');
    dragImage.className = 'node-drag-image';
    dragImage.textContent = node.label;
    document.body.appendChild(dragImage);
    e.dataTransfer.setDragImage(dragImage, dragOffset.x, dragOffset.y);
    setTimeout(() => document.body.removeChild(dragImage), 0);
  };

  /**
   * 处理拖拽进入SVG容器
   */
  const handleDragEnter = (e: DragEvent) => {
    if (!isDragging.value) return;
    e.preventDefault();
    isOverSvg.value = true;
  };

  /**
   * 处理拖拽离开SVG容器
   */
  const handleDragLeave = (e: DragEvent) => {
    if (!isDragging.value) return;
    e.preventDefault();
    isOverSvg.value = false;
  };

  /**
   * 处理拖拽经过SVG容器
   */
  const handleDragOver = (e: DragEvent) => {
    if (!isDragging.value || !svgContainer.value) return;
    e.preventDefault();

    // 更新拖拽位置
    const position = convertToSVGCoordinates(e);
    dragPosition.x = position.x - dragOffset.x;
    dragPosition.y = position.y - dragOffset.y;
  };

  /**
   * 处理节点放置
   */
  const handleDrop = (e: DragEvent) => {
    console.log('拖拽结束前选中状态:', workflowStore.state.selectedNodeIds);
    if (!isDragging.value || !draggedNode.value || !svgContainer.value) return;
    e.preventDefault();

    // 计算放置位置
    const position = convertToSVGCoordinates(e);
    const dropPosition = {
      x: position.x - dragOffset.x,
      y: position.y - dragOffset.y
    };

    // 添加新节点并更新视图
    workflowStore.addNode(draggedNode.value.data, dropPosition);
    resetDragState();
    updateTransform();

    // 强制更新视图以确保正确渲染
    nextTick(() => {
      if (svgContainer.value) {
        const rect = svgContainer.value.getBoundingClientRect();
        svgContainer.value.setAttribute('viewBox', `0 0 ${rect.width - 1} ${rect.height - 1}`);
        requestAnimationFrame(() => {
          svgContainer.value?.setAttribute('viewBox', `0 0 ${rect.width} ${rect.height}`);
          updateTransform();
        });
      }
    });
    console.log('拖拽结束后选中状态:', workflowStore.state.selectedNodeIds);
  };

  /**
   * 处理拖拽结束
   */
  const handleDragEnd = () => {
    resetDragState();
  };

  /**
   * 重置拖拽状态
   */
  const resetDragState = () => {
    isDragging.value = false;
    draggedNode.value = null;
    dragPosition.x = 0;
    dragPosition.y = 0;
    isOverSvg.value = false;
  };

  /**
   * 计算预览位置
   */
  const previewPosition = computed(() => {
    if (!isDragging.value || !draggedNode.value || !isOverSvg.value) return null;
    return dragPosition;
  });

  /**
   * 设置拖拽偏移量
   */
  const setDragOffset = (offset: Position) => {
    dragOffset.x = offset.x;
    dragOffset.y = offset.y;
  };

  // 返回公共接口
  return {
    isDragging,
    draggedNode,
    previewPosition,
    handleNodeDragStart,
    handleDragEnter,
    handleDragLeave,
    handleDragOver,
    handleDrop,
    handleDragEnd,
    setDragOffset
  };
} 